import React, { Component } from 'react';
import { user_login } from '../utils/api'
import './Login.scss'
import { Toast } from 'antd-mobile'
import { debounce } from '../utils/tools'

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            pwd: ''
        }

    }

    handleChange(e) {
        this.setState({
            // phone: e.target.value
            [e.target.name]: ((e.target.value == 'checkbox' || e.target.value == 'radio') ? e.target.checked : e.target.value)
        })
    }

    // 点击校验账号密码是否合适，登录成功就跳转到主页
    login() {
        if (/^1[3-9]\d{9}$/.test(this.state.phone) == false) {
            Toast.show({
                icon: 'fail',
                content: '请输入合法的手机号!',
            })
        } else {
            user_login({ phone: this.state.phone, pass: this.state.pwd }).then((res) => {
                if (res.data.code == 200) {
                    Toast.show({
                        icon: 'success',
                        content: '登录成功！',
                    })
                    //保存用户信息,token
                    localStorage.setItem('token', res.data.token);
                    localStorage.setItem('userinfo', JSON.stringify(res.data.userinfo));
                    this.props.history.push({ pathname: '/index/home' });
                } else {
                    Toast.show({
                        icon: 'fail',
                        content: '登录失败!',
                    })
                }
            })
        }
    }

    // 点击注册跳转到注册页
    register() {
        this.props.history.push({ pathname: '/register' });
    }

    render() {
        return (
            <div className='login' style={{ backgroundImage: "url(" + require("../bg.webp") + ")" }}>
                {/* 将非受控元素变成受控元素，通过value和onChange绑定实现 */}
                {/* value绑定，将组件状态绑定到元素的value属性 */}
                {/* onChange绑定，当元素的值发生改变时更新元素的值到组件状态 */}
                <div className="title">
                    <h2>登 录 页</h2>
                </div>
                <div className="block">
                    <input type="text" name='phone' placeholder='请输入手机号' value={this.state.phone} onChange={(e) => {
                        this.handleChange(e)
                    }} />
                </div>
                <div className="block">
                    <input type="password" name='pwd' placeholder='请输入密码' value={this.state.pwd} onChange={(e) => {
                        this.handleChange(e)
                    }} />
                </div>
                <div className="block1">
                    <input type="button" value="登录" onClick={() => { this.login() }} />
                    <span onClick={() => { debounce(this.register()) }}>注册</span>
                </div>
            </div>
        );
    }
}

export default Login;